import React, { useEffect, useState } from 'react';
import {
    Card,
    Pagination,
} from 'tdesign-react';
import moment from 'moment';
import * as XLSX from 'xlsx';

import axios from 'axios';
import {
    Button,
    DatePicker,
    Form,
    Input,
    Space,
    Table,
    Modal,
    Tabs,
} from 'antd';

import { DownloadOutlined } from '@ant-design/icons';
import type { PaginationProps, TableProps } from 'antd';

import { message } from 'antd';
axios.defaults.baseURL = 'http://127.0.0.1:3000/zlq'


export default function Operation_log() {
    const [form] = Form.useForm()

    const gender = Form.useWatch('gender', form);
    console.log('gender', gender);


    const [id, setId] = useState('')
    const [name, setName] = useState('')
    const [login, setLogin] = useState('')
    const [ip, setIp] = useState('')
    const [mac, setMac] = useState('')

    // const getDictionary_cate = async () => {
    //     let { data: { code, dictionary_cateList } } = await axios.get(`/dictionary_cateList?name=${dictionary_cateName}`)
    //     if (code == 200) {
    //         getDictionary_cate(dictionary_cateList)
    //     }
    // }

    let [so_model, setSo_model] = useState('')
    let [so_operator, setSo_operator] = useState('')
    let [so_operationTime, setSo_operationTime] = useState('')


    const getJournalList = async () => {
        // 检查 so_time 是否存在，并且是有效的时间格式
        let { data: { code, journalList, total } } = await axios.get(`/journalList`, {
            params: {
                page: page,
                pagesize: pageSize,
                model: so_model,
                operator: so_operator ? so_operator : '', // 如果 so_time 有值，传递它，否则传递空字符串
                operationTime: so_operationTime,
            }
        });

        if (code === 200) {
            setTotal(total);
            setData(journalList);
        }
    };

    let page = 1
    let pageSize = 5
    let [total, setTotal] = useState(0)

    const onChange: PaginationProps['onChange'] = (pageInfo) => {
        page = pageInfo.current
        pageSize = pageInfo.pageSize
        getJournalList()
        console.log(pageInfo);
    };
    const onPageSizeChange: PaginationProps['onPageSizeChange'] = (size) => {
        pageSize = size
        getJournalList()
        console.log('page-size:', size);
    };
    const onCurrentChange: PaginationProps['onCurrentChange'] = (index, pageInfo) => {
        page = index
        getJournalList()
        console.log(`转到第${index}页`);
        console.log(pageInfo);
    };

    //词条表格
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            render: (_, __, index) => <a>{index + 1}</a>,  // 使用行索引作为序号，index 从 0 开始，+1 让序号从 1 开始
        },
        {
            title: '系统模块',
            dataIndex: 'module',
            key: 'module',
        },
        {
            title: '操作类型',
            dataIndex: 'cate',
            key: 'cate',
        },
        {
            title: '操作人员',
            dataIndex: 'operator',
            key: 'operator',
        },
        {
            title: '操作地址',
            dataIndex: 'ipAddress',
            key: 'ipAddress',
        },
        {
            title: '操作时间',
            dataIndex: 'operationTime',
            key: 'operationTime',
            render: (text) => {
                // 通过 Date 对象来格式化时间
                const date = new Date(text);
                const formattedDate = date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                });
                return formattedDate; // 返回格式化后的日期字符串
            },
        },
        {
            title: '消耗时间',
            dataIndex: 'responseTime',
            key: 'responseTime',
        },

        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => { getEdit(record) }}>日志详细</a>
                </Space>
            ),
        },
    ];

    const [data, setData] = useState<DataType[]>([]);

    //词条回显
    useEffect(() => {
        form.setFieldsValue({
            login: login,
            mac: mac,
            ip: ip,
            name: name,
        });
    }, [name, login, mac, ip,]);

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    //新增词条弹框
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        setId('')
        setIp("")
        setLogin("")
        setMac("")
        setName('')
        handleOk()
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
        setList([])
    };


    const [dictionary_cateName, setDictionary_cateName] = useState('')


    const getSo = () => {
        getJournalList();
    };
    let [list, setList] = useState([]);

    const getEdit = (id: any) => {
        showModal();
        console.log(id);
        setId(id._id);
        setIp(id.ip);
        setLogin(id.login);
        setName(id.name);
        setMac(id.mac);
        // 保留现有数据，更新 list
        setList((prevList) => [...prevList, id]);
        const formattedTime = new Intl.DateTimeFormat('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
        }).format(new Date(id.operationTime));
        setFormTime(formattedTime)
    }
    let [formtime,setFormTime] = useState('')
    // 添加导出功能
    const exportToExcel = () => {
        // 将表格数据转换为合适的格式
        const dataForExport = data.map((item, index) => ({
            序号: index + 1,
            系统模块: item.module,
            操作类型: item.cate,
            操作人员: item.operator,
            操作地址: item.ipAddress,
            操作时间: new Date(item.operationTime).toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
            }),
            消耗时间: item.responseTime,
        }));

        // 创建一个工作表并将其转换为 Excel 文件
        const ws = XLSX.utils.json_to_sheet(dataForExport);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '日志数据');

        // 导出 Excel 文件
        XLSX.writeFile(wb, '操作日志.xlsx');
    };


    useEffect(() => {
        // getDictionary_cate()
        getJournalList()
    }, [])
    return (
        <div>
            <div style={{ marginRight: "20px", }}>
                <Card bordered style={{ width: "1000px", marginBottom: "10px" }}>
                    <div style={{ display: 'flex' }}>
                        <Form.Item label="系统模块" name="so_model" initialValue={so_model} style={{ marginRight: "10px" }}>
                            <Input
                                value={so_model}
                                onChange={(e) => setSo_model(e.target.value)}  // 更新输入框的值
                            />
                        </Form.Item>
                        <Form.Item label="操作人员" name="so_operator" initialValue={so_operator} style={{ marginRight: "10px" }}>
                            <Input
                                value={so_operator}
                                onChange={(e) => setSo_operator(e.target.value)}  // 更新输入框的值
                            />
                        </Form.Item>
                        <Form.Item label="操作时间" name="so_operationTime" initialValue={so_operationTime ? moment(so_operationTime) : null} style={{ marginRight: "10px" }}>
                            <DatePicker
                                value={so_operationTime ? moment(so_operationTime) : null}  // 如果 so_time 存在，则转换为 moment 对象
                                onChange={(date, dateString) => setSo_operationTime(dateString)}  // 更新日期值
                                style={{ width: '100%' }}
                                format="YYYY-MM-DD"  // 自定义日期格式
                            />
                        </Form.Item>
                        <Button style={{ marginLeft: "50px" }} type="primary" htmlType="submit" onClick={() => { getSo() }}>
                            搜索
                        </Button>
                    </div>
                </Card>
            </div>

            <div style={{ height: "500px" }}>
                <Card
                    bordered
                    headerBordered
                    style={{ height: "600px", width: "1000px" }}
                >
                    <div style={{ marginBottom: "50px" }}>
                        <Button style={{ float: "right" }}  type="primary" icon={<DownloadOutlined />} onClick={exportToExcel}></Button>
                    </div>

                    <Modal title="日志详情" closable={false} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
                        {
                            list.map((item) => {
                                return (
                                    <div style={{ maxWidth: 600 }}>
                                        <p>
                                            <span>操作人员：</span><span>{item.operator}</span>
                                        </p>
                                        <p>
                                            <span>操作地址：</span><span>{item.ipAddress}</span>
                                        </p>
                                        <p>
                                            <span>操作模块：</span><span>{item.module}</span>
                                        </p>
                                        <p>
                                            <span>操作类型：</span><span>{item.cate}</span>
                                        </p>
                                        <p>
                                            <span>请求地址：</span><span>{item.requestUrl}</span>
                                        </p>
                                        <p>
                                            <span>请求方式：</span><span>{item.requestMethod}</span>
                                        </p>
                                        <p>
                                            <span>操作方法：</span><span>{item.operationMethod}</span>
                                        </p>
                                        <p>
                                            <span>请求参数：</span><span>{JSON.stringify(item.requestParams)}</span>
                                        </p>
                                        <p>
                                            <span>消耗时间: </span><span>{item.responseTime}</span>
                                        </p>
                                        <p>
                                            <span>操作时间：</span><span>{formtime}</span>
                                        </p>
                                    </div>

                                )
                            })
                        }
                    </Modal>

                    <div>
                        <Table<DataType> pagination={false} rowSelection={rowSelection} columns={columns} dataSource={data} />
                    </div>
                    <Pagination
                        total={total}
                        defaultPageSize={pageSize}
                        onChange={onChange}
                        onCurrentChange={onCurrentChange}
                        onPageSizeChange={onPageSizeChange}
                    />
                </Card>
            </div >
        </div >
    );
}